import 'dart:math';

import 'package:flutter/material.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import 'package:kq_flutter_core_widget/extentions/kq_extentions.dart';
import 'package:kq_flutter_core_widget/resources/images.dart';
import '../../resources/kq_theme_colors.dart';
import 'package:kq_flutter_core_widget/utils/file_preview_util.dart';
import 'package:kq_flutter_core_widget/widgets/image/kq_image.dart';
import 'package:kq_flutter_core_widget/widgets/imageBox/kq_image_box.dart';

import '../../theme/kq_theme_manager.dart';
import '../dialog/kq_file_picker.dart';
import '../divider/kq_divider.dart';
import 'entity/kq_form_entity.dart';

class KqImageBoxItemView extends StatefulWidget {
  /// 数据实体类
  final KqFormEntity entity;

  /// 图片添加按钮点击回调
  final Function(KqFormEntity entity, KqImageBoxState state)? onAddTap;

  /// 图片删除按钮点击回调
  final Function(KqFormEntity entity, ImageUrl imageUrl, int position,
      KqImageBoxState state)? onDeleteTap;

  /// 图片点击回调
  final Function(KqFormEntity entity, ImageUrl imageUrl, int position,
      KqImageBoxState state)? onImageTap;

  const KqImageBoxItemView(
      {Key? key,
      required this.entity,
      this.onAddTap,
      this.onDeleteTap,
      this.onImageTap})
      : super(key: key);

  @override
  KqImageBoxItemViewState createState() => KqImageBoxItemViewState();
}

class KqImageBoxItemViewState extends State<KqImageBoxItemView> {
  @override
  void initState() {
    widget.entity.widgetState = this;
    super.initState();
  }

  /// 主动刷新方法
  update() {
    if (mounted) {
      setState(() {});
    }
  }


  /// 定位到该条数据，滚动到屏幕中央
  location(ScrollController? scrollController) {
    if (scrollController == null) {
      return;
    }
    //拿到控件的位置
    var position = context.position();
    var dy = position?.dy;
    if (scrollController.hasClients && dy != null) {
      var util = KqScreenUtil();
      var screenHeight = util.screenHeight;
      var targetY =
          scrollController.offset + dy - screenHeight / 2;
      var maxY = scrollController.position.maxScrollExtent;
      scrollController.jumpTo(max(0, min(targetY, maxY)));
    }
  }

  /// 拼接提交的valueForSubmit
  String? getSubmitValues({join = ','}) {
    if (widget.entity.imageUrls == null || widget.entity.imageUrls!.isEmpty) {
      return null;
    }
    var values = [];
    for (var url in widget.entity.imageUrls!) {
      if (url.valueForSubmit != null) {
        values.add(url.valueForSubmit);
      }
    }
    return values.isEmpty ? null : values.join(join);
  }

  @override
  Widget build(BuildContext context) {
    // 如果外层实体是反复重新创建的，则需要在此重新赋值
    widget.entity.widgetState = this;
    // 背景颜色
    var bgColor = widget.entity.backgroundColor ?? KqThemeColors.bgDialog;
    return Visibility(
      visible: widget.entity.visible,
      child: Column(
        children: [
          Container(
            color: bgColor,
            padding: EdgeInsets.only(
                top: widget.entity.paddingVertical ??
                    KqThemeManager.instance
                        .getConfig()
                        .formConfig
                        .paddingVertical ??
                    24.r,
                bottom: widget.entity.paddingVertical ??
                    KqThemeManager.instance
                        .getConfig()
                        .formConfig
                        .paddingVertical ??
                    24.r,
                right: widget.entity.paddingHorizontal ??
                    KqThemeManager.instance
                        .getConfig()
                        .formConfig
                        .paddingHorizontal ??
                    24.r),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Row(
                  children: <Widget>[
                    Expanded(
                        child: Container(
                      padding: EdgeInsets.only(right: widget.entity.titleRightMargin ?? (widget.entity.title.isNotEmpty ? 40.r : 0)),
                      child: Row(
                        children: <Widget>[
                          ///是否必填
                          Container(
                            alignment: Alignment.centerRight,
                            width: widget.entity.paddingHorizontal ??
                                KqThemeManager.instance
                                    .getConfig()
                                    .formConfig
                                    .paddingHorizontal ??
                                24.r,
                            padding: EdgeInsets.only(right: 2.r),
                            child: Text(
                              "∗",
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                  fontSize: KqThemeManager.instance
                                          .getConfig()
                                          .formConfig
                                          .mustInputFontSize ??
                                      24.sp,
                                  color: widget.entity.mustInput &&
                                          widget.entity.isEditable()
                                      ? KqThemeColors.textRed
                                      : KqThemeColors.bgTransparent),
                            ),
                          ),

                          ///标题
                          LimitedBox(
                            maxWidth: KqThemeManager.instance
                                    .getConfig()
                                    .formConfig
                                    .titleMaxWidth ??
                                200.r,
                            child: Text(
                              widget.entity.title,
                              maxLines: widget.entity.multiline ? null : 1,
                              overflow: widget.entity.multiline
                                  ? null
                                  : TextOverflow.ellipsis,
                              style: widget.entity.titleStyle ??
                                  TextStyle(
                                      fontSize: KqThemeManager.instance
                                              .getConfig()
                                              .formConfig
                                              .titleFontSize ??
                                          16.sp,
                                      color: widget.entity.titleColor ??
                                          KqThemeColors.text26),
                            ),
                          ),

                          /// 自定义布局，来自实体类
                          widget.entity.customLeftView != null
                              ? widget.entity.customLeftView!(widget.entity)
                              : Container(),
                        ],
                      ),
                    )),

                    /// 选择进度
                    Visibility(
                        visible: !widget.entity.hideImageBoxCountInfo,
                        child: Text(
                          '${widget.entity.imageUrls?.length ?? 0}/${widget.entity.maxQty ?? 8}',
                          style: TextStyle(
                              fontSize: KqThemeManager.instance
                                      .getConfig()
                                      .formConfig
                                      .contentFontSize ??
                                  16.sp,
                              color: widget.entity.contentColor ??
                                  KqThemeColors.text59),
                        )),
                  ],
                ),
              ],
            ),
          ),

          /// 图片容器
          widget.entity.imageUrls == null ||
                  (widget.entity.imageUrls!.isEmpty && !widget.entity.isEditable())
              ? Container()
              : Container(
                  color: bgColor,
                  padding: EdgeInsets.only(
                      left: 24.r, right: 24.r, top: 0, bottom: 10.r),
                  child: KqImageBox(
                    urls: widget.entity.imageUrls!,
                    maxQty: widget.entity.maxQty?.toInt() ?? 8,
                    cols: widget.entity.imageBoxCols,
                    customAddPic: Images.commonIcJiazhaopian,
                    onAddTap: (urls, state) {
                      if (widget.entity.onAddTap == null &&
                          widget.onAddTap == null) {
                        //默认点击添加按钮实现
                        KqFilePicker(maxCount: (widget.entity.maxQty?.toInt() ?? 8) - state.count())
                            .choosePhoto(
                          context,
                          (files) {
                            for (var file in files) {
                              state.addImage(ImageUrl(
                                  imageType: ImageType.file,
                                  url: file.filePath!));
                            }
                          },
                        );
                        return;
                      }
                      if (widget.entity.onAddTap != null) {
                        widget.entity.onAddTap!(widget.entity, state);
                      }
                      if (widget.onAddTap != null) {
                        widget.onAddTap!(widget.entity, state);
                      }
                    },
                    onDeleteTap: (urls, imageUrl, position, state) {
                      if (widget.entity.onDeleteTap == null &&
                          widget.onDeleteTap == null) {
                        state.remove(imageUrl);
                        return;
                      }
                      if (widget.entity.onDeleteTap != null) {
                        widget.entity.onDeleteTap!(
                            widget.entity, imageUrl, position, state);
                      }
                      if (widget.onDeleteTap != null) {
                        widget.onDeleteTap!(
                            widget.entity, imageUrl, position, state);
                      }
                    },
                    onImageTap: (urls, imageUrl, position, state) {
                      if (widget.entity.onImageTap == null &&
                          widget.onImageTap == null) {
                        FilePreviewUtil.previewImg(widget.entity.imageUrls!);
                        return;
                      }
                      if (widget.entity.onImageTap != null) {
                        widget.entity.onImageTap!(
                            widget.entity, imageUrl, position, state);
                      }
                      if (widget.onImageTap != null) {
                        widget.onImageTap!(
                            widget.entity, imageUrl, position, state);
                      }
                    },
                    onChanged: () {
                      setState(() {});
                    },
                    editable: widget.entity.isEditable(),
                  ),
                ),

          /// 分割线
          Visibility(
              visible: !widget.entity.hideDivider, child: const KqDivider())
        ],
      ),
    );
  }
}
